const toggleBtn = document.querySelectorAll('.zl');
const detailModal = document.getElementById('detailModal');
const closeBtn = document.getElementById('closeBtn');
const followButtons = document.querySelectorAll('.follows');
const followButton = document.querySelector('.follow');
const unfollowButtons = document.querySelectorAll('.unfollows');


//弹窗
function showCustomAlert(message, duration) {
    let customAlert = document.getElementById('customAlert');
    if (!customAlert) {
        div_outter=document.createElement('div');
        customAlert = document.createElement('div');
        customAlert.id = 'customAlert';
        // customAlert.style.margin='7px 12px';
        const alertMessage = document.createElement('p');
        alertMessage.id = 'alertMessage';
        customAlert.appendChild(alertMessage);

        document.body.appendChild(customAlert);
    }

    const alertMessage = document.getElementById('alertMessage');

    alertMessage.textContent = message;
    if(alertMessage.textContent==null){
        customAlert.style.display = 'none';
    }

    customAlert.style.display = 'block';
    setTimeout(() => {
        customAlert.style.display = 'none';
    }, duration);
}

// 显示详细信息
if (toggleBtn.length > 0 && detailModal && closeBtn) {
    // 遍历所有匹配的按钮，为每个按钮添加点击事件监听器
    toggleBtn.forEach(function (button) {
        button.addEventListener('click', function () {
            if (detailModal.style.display === 'none') {
                detailModal.style.display = 'block';
                this.textContent = '收起详细信息';
                document.body.classList.add('modal-open');
            } else {
                detailModal.style.display = 'none';
                this.textContent = '显示详细信息';
                document.body.classList.remove('modal-open');
            }
        });
    });
    closeBtn.addEventListener('click', function () {
        detailModal.style.display = 'none';
        // 遍历所有按钮，将文本重置为显示详细信息
        toggleBtn.forEach(function (button) {
            button.textContent = '显示详细信息';
        });
        document.body.classList.remove('modal-open');
    });
}

//关注
followButtons.forEach((button) => {
    console.log('初始类名:', button.className);
    button.addEventListener('click', function () {
        console.log('点击时类名:', this.className);
        if (this.classList.contains('follows')) {
            this.textContent = '已关注';
            this.classList.replace('follows', 'unfollows');
        } else {
            this.textContent = '+关注他';
            this.classList.replace('unfollows', 'follows');
        }
        console.log('点击后类名:', this.className);
    });

    button.addEventListener('mouseover', function () {
        if (this.classList.contains('unfollows')) {
            this.textContent = '取消关注';
        }
    });

    button.addEventListener('mouseout', function () {
        if (this.classList.contains('unfollows')) {
            this.textContent = '已关注';
        }
    });
});
if (followButton) {
    console.log('初始类名:', followButton.className);
    followButton.addEventListener('click', function () {
        console.log('点击时类名:', this.className);
        if (this.classList.contains('follow')) {
            this.textContent = '已关注';
            this.classList.replace('follow', 'unfollow');
        } else {
            this.textContent = '+关注他';
            this.classList.replace('unfollow', 'follow');
            }
            })
            }//显示用户信息
const detailBtn = document.querySelector('.zl');
const userId = detailBtn.dataset.userId;
const url = `http://localhost:8080/admin/toUpdateUserPage?id=${userId}`;
// 使用AJAX获取用户数据
$.ajax({
    dataType: 'json', // 明确指定返回JSON格式
    url:url,
    method: 'GET',
    success: function(user) {
        console.log('获取用户数据成功:', user); // 用于调试
        document.querySelector('.name').textContent = user.user.username;
        document.getElementById('women').textContent = user.user.gender;
        document.getElementById('uimg').src= user.user.avatar;
        document.getElementById('userGender').textContent = user.user.gender;
        document.getElementById('userLocation').textContent = user.user.location;
        document.getElementById('userIndustry').textContent = user.user.industry;
        document.getElementById('userBio').textContent = user.user.bio;
        console.log(user.user.gender);
        console.log( user.user.location);
        console.log( user.user.industry);
        console.log(user);
    },
    error: function(error) {
        console.error('AJAX 请求错误:', error);
         showCustomAlert('网络错误，请重试');
    }
});
//背景图片
function uploadBackground(file) {
    const formData = new FormData();
    formData.append('file', file);
     showCustomAlert("正在上传")
    $.ajax({
        url: `/userHomepage/updateBackground`, // 与后端接口路径一致
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
            if (response.success) {
                // 关键：动态更新 img.src
                const imgElement = document.getElementById('uimgs');
                imgElement.src = response.url; // 直接使用后端返回的 URL
                localStorage.setItem('backgroundUrl', response.url);
                showCustomAlert('背景图更新成功');
            } else {
                 showCustomAlert('上传失败：' + response.message);
            }
        },
        error: function (xhr, status, error) {
            console.error('上传失败:', error);
             showCustomAlert('网络错误，请重试');
        }
    });
}
document.querySelector('.photo').addEventListener('click', function () {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.onchange = function (e) {
        const file = e.target.files[0];
        if (file) {
            uploadBackground(file);
        }
    };
    fileInput.click();
});
window.addEventListener('load', function () {
    const savedUrl = localStorage.getItem('backgroundUrl');
    if (savedUrl) {
        document.getElementById('uimgs').src = savedUrl;
    }
});

//举报
document.addEventListener('DOMContentLoaded', function () {
    const reportButtons = document.querySelectorAll('.report');
    const reportModal = document.getElementById('reportModal');
    const closeButton2 = document.querySelector('.close2');
    const submitReportButton = document.getElementById('submitReport');
    const reportTypeButtons = document.querySelectorAll('.report-type');

    // 打开模态框的函数
    function openReportModal() {
        reportModal.style.display = 'block';
    }

    // 关闭模态框的函数
    function closeReportModal() {
        reportModal.style.display = 'none';
        resetReportButtons();
    }

    // 重置举报类型按钮和提交按钮状态的函数
    function resetReportButtons() {
        reportTypeButtons.forEach(button => button.classList.remove('active'));
        submitReportButton.classList.remove('active');
        submitReportButton.disabled = true;
    }


    // 为所有类名为 report 的按钮绑定点击事件
    reportButtons.forEach(button => {
        button.addEventListener('click', openReportModal);
    });

    // 为关闭按钮绑定点击事件
    closeButton2.addEventListener('click', closeReportModal);

    // 点击模态框外部关闭模态框
    window.addEventListener('click', function (event) {
        if (event.target === reportModal) {
            closeReportModal();
        }
    });

    // 为举报类型按钮绑定点击事件
    reportTypeButtons.forEach(button => {
        button.addEventListener('click', function () {
            reportTypeButtons.forEach(otherButton => otherButton.classList.remove('active'));
            this.classList.add('active');
            submitReportButton.classList.add('active');
            submitReportButton.disabled = false;
        });
    });

    // 初始时禁用提交按钮
    submitReportButton.disabled = true;

    // 为提交按钮绑定点击事件
    submitReportButton.addEventListener('click', function () {
        if (!this.disabled) {
            confirms('举报已提交');
            closeReportModal();
        }
    });
});

//删除帖子
document.addEventListener('click', function(event) {
    const deleteButton = event.target.closest('.delete-article');
    if (deleteButton) {
        handleDelete(deleteButton.dataset.postId);
    }
});

function handleDelete(postId) {
    if (!postId) {
        confirms("参数错误", () => {});
        return;
    }
    confirms("确定要删除这篇文章吗？此操作不可撤销。", (inConfirmed) => {
        if (inConfirmed) {
            // 通过 postId 找到对应的删除按钮（需要调整选择器）
            const deleteButton = document.querySelector(`.delete-article[data-post-id="${postId}"]`);
            $.ajax({
                url: "/posts/delete",
                method: "POST",
                data: {id: postId},
                success: function (response) {
                    // 从DOM中移除对应的文章元素
                    const postElement = deleteButton.closest('.question-container');
                    if (postElement) {
                        postElement.remove();
                        showCustomAlert("文章删除成功");
                    }
                },
                error: function (error) {
                    console.error("删除失败:", error.responseText);
                }
            });
        }
    });
}
//删除视频
document.addEventListener('click', function(event) {
    const deleteVideoButton = event.target.closest('.delete-video');
    if (deleteVideoButton) {
        handleDeletes(deleteVideoButton.dataset.videoId);
    }
});

function handleDeletes(videoId) {
    if (!videoId) {
        confirms("参数错误", () => {
        });
        return;
    }
    confirms("确定要删除这个视频吗？此操作不可撤销。", (inConfirmed) => {
        if (inConfirmed) {
            // 通过 postId 找到对应的删除按钮（需要调整选择器）
            const deleteVideoButton = document.querySelector(`.delete-video[data-video-id="${videoId}"]`);
            $.ajax({
                url: "/videos/delete",
                method: "POST",
                data: {id: videoId},
                success: function (response) {
                    // 从DOM中移除对应的文章元素
                    const postElement = deleteVideoButton.closest('.question-container');
                    if (postElement) {
                        postElement.remove();
                        showCustomAlert("视频删除成功");
                    }
                },
                error: function (error) {
                    console.error("删除失败:", error.responseText);
                }
            });
        }
    });
}
//删除想法
document.addEventListener('click', function(event) {
    // 统一使用deleteButton作为变量名
    const deleteButton = event.target.closest('.delete-idea');
    if (deleteButton) {
        // 获取data-post-id属性值
        const thoughtId = deleteButton.dataset.postId;
        console.log("获取到的thoughtId:", thoughtId); // 调试用
        handleDeleteIdea(thoughtId);
    }
});

function handleDeleteIdea(thoughtId) {
    // 验证参数
    if (!thoughtId) {
        confirms("参数错误：缺少想法ID", () => {});
        return;
    }

    confirms("确定要删除这个想法吗？此操作不可撤销。", (inConfirmed) => {
        if (inConfirmed) {
            // 不需要重新选择按钮，直接使用传入的参数
            $.ajax({
                url: "/thought/delete",
                method: "POST",
                data: {id: thoughtId},
                success: function (response) {
                    // 验证服务器返回状态
                    if (response && response.message === "删除成功") {
                        // 从DOM中移除对应的想法元素
                        const postElement = document.querySelector(`.delete-idea[data-post-id="${thoughtId}"]`).closest('.question-container');
                        if (postElement) {
                            postElement.remove();
                            showCustomAlert("想法删除成功",3000);
                        }
                    } else {
                        const errorMsg = response && response.message ? response.message : "删除失败，未知错误";
                        console.error("删除失败:", errorMsg);
                        showCustomAlert(errorMsg,3000);
                    }
                },
                error: function (error) {
                    console.error("AJAX请求错误:", error);
                    showCustomAlert("网络错误，请稍后重试",3000);
                }
            });
        }
    });
}
//关注
// 使用事件委托绑定点击事件到父容器
document.querySelector('.tab-content').addEventListener('click', function(e) {
    // 只处理关注/取消关注按钮的点击
    if (e.target.classList.contains('unfollows') || e.target.classList.contains('follows')) {
        const followButton = e.target;
        const userId = followButton.getAttribute('data-user-id');
        console.log('User ID:', userId);

        if (!userId) {
            showCustomAlert('用户ID获取失败', 3000);
            return;
        }

        if (followButton.classList.contains('unfollows')) {
            // 取消关注
            $.ajax({
                url: `/cancelFollow?id=${userId}`,
                type: 'POST',
                success: function(result) {
                    showCustomAlert('取消关注成功', 3000);
                    // 切换状态
                    followButton.classList.remove('unfollows');
                    followButton.classList.add('follows');
                    followButton.textContent = '+关注他';
                },
                error: function(error) {
                    showCustomAlert('取消关注失败: ' + error.statusText, 3000);
                }
            });
        } else {
            // 关注
            $.ajax({
                url: `/followOthers?id=${userId}`,
                type: 'GET',
                success: function(result) {
                    showCustomAlert('关注成功', 3000);
                    // 切换状态
                    followButton.classList.remove('follows');
                    followButton.classList.add('unfollows');
                    followButton.textContent = '已关注';
                },
                error: function(error) {
                    showCustomAlert('关注失败: ' + error.statusText, 3000);
                }
            });
        }
    }
});
//从主页关注
follow_button.addEventListener('click', function() {
    let userId = this.value;
    console.log(userId);
    if (this.classList.contains('unfollows')) {
        // 当前是已关注状态，执行取消关注逻辑
        $.ajax({
            url: `/cancelFollow?id=${userId}`,
            type: 'POST',
            success: function(result) {
                showCustomAlert('取消关注成功', 3000);
                follow_button.classList.remove('follows');
                follow_button.textContent = '关注';
            },
            error: function(error) {
                showCustomAlert('取消关注失败: ' + error.statusText, 3000);
            }
        });
    }
    else {
        // 当前是未关注状态，执行关注逻辑
        $.ajax({
            url: `/followOthers?id=${userId}`,
            type: 'GET',
            success: function(result) {
                showCustomAlert('关注成功', 3000);
                follow_button.classList.add('follows');
                follow_button.textContent = '取消关注';
            },
            error: function(error) {
                showCustomAlert('关注失败: ' + error.statusText, 3000);
            }
        });
    }
})
//弹窗
function confirms(content, callback) {
    return new Promise((resolve) => {
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'v-modal';
        overlay.style.cssText = 'position: fixed; inset: 0; z-index: 2000; background-color: rgba(0,0,0,0.5);';

        // 创建对话框
        const dialog = document.createElement('div');
        dialog.className = 'el-message-box__wrapper';
        dialog.style.cssText = 'position: fixed; inset: 0; z-index: 2001; display: flex; align-items: center; justify-content: center;';
        dialog.innerHTML = `
      <div class="el-message-box">
        <div class="el-message-box__header">
          <div class="el-message-box__title"><span>系统提示</span></div>
        </div>
        <div class="el-message-box__content">
          <div class="el-message-box__message"><p>${content}</p></div>
        </div>
        <div class="el-message-box__btns">
          <button type="button" class="el-button el-button--default el-button--small cancel-btn">
            <span>取消</span>
          </button>
          <button type="button" class="el-button el-button--default el-button--small el-button--primary confirm-btn">
            <span>确认</span>
          </button>
        </div>
      </div>
    `;

        // 添加到文档
        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 绑定确认按钮事件
        const confirmBtn = dialog.querySelector('.confirm-btn');
        confirmBtn.addEventListener('click', () => {
            removeDialog(overlay, dialog); // 关闭弹窗
            callback(true); // 调用回调并传入结果（true=确认）
        });
        // 绑定取消按钮事件
        const cancelBtn = dialog.querySelector('.cancel-btn');
        cancelBtn.addEventListener('click', () => {
            resolve(false); // 点击取消返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 绑定遮罩层点击事件
        overlay.addEventListener('click', () => {
            resolve(false); // 点击遮罩返回 false
            removeDialog(overlay, dialog); // 关闭弹窗
        });

        // 统一关闭弹窗函数
        function removeDialog(overlay, dialog) {
            overlay.remove();
            dialog.remove();
        }
    });
}
